package com.shop.pay.controller;

import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.internal.util.AlipaySignature;
import com.alipay.api.request.AlipayTradePagePayRequest;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;



/**
 * @author ghy
 * @version 1.0
 * @date 2020-11-05
 */
@Controller
@RequestMapping("/pay")
public class PayController {

    private HttpServletRequest httpRequest;
    private HttpServletResponse httpResponse;
    private String aliPayPublicKey = "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAnsIDh0f3dp2BVPGTobJA9Vyv0q+yVaOWgwrUf19gesAFokj5uCsWPqUNBP39pjobvbdHytSgT8yLL8O2S/obdz5xsmc2BJGetLtDWqy3HjgQfLlv6L1einHyM1hhCDj0D+0zITLgavexsqvgzOxMHChsgoc+Nyj0u6HEWy0eTBJIR1w+C7DeOoMHXE4eb02cTo0qWpNBhU0ZCW8ziiNNN/3CacRjETb1n6u7iUT0TULM28zusGRsWpBWgM/1imws+XJkjNnkUXdeXxwdT9Q6nZzqAsCTyeSM4vun1dVU74u/a1dwOj28D9fqaYAHJz7/ppyge8qTdwWQHVqdL65MywIDAQAB";


    /**
     * 验签接口
     * @param request
     * @param response
     * @param orderno
     * @param money
     */
    @PostMapping("/notifyurl")
    public void notify(HttpServletRequest request, HttpServletResponse response, String orderno, Double money) {
        try {
            Map<String, String[]> parameterMap = request.getParameterMap();
            System.out.println(parameterMap);

            Map<String, String> paramsMap = new HashMap<>();

            for (String key : parameterMap.keySet()) {
                if(!"money".equalsIgnoreCase(key) && !"orderno".equalsIgnoreCase(key)) {
                    paramsMap.put(key, parameterMap.get(key)[0]);
                }

            }

            //将异步通知中收到的所有参数都存放到 map 中
            //1.判断支付接口是不是支付宝调用的
            boolean signVerified = AlipaySignature.rsaCheckV1(
                    paramsMap,
                    "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAnsIDh0f3dp2BVPGTobJA9Vyv0q+yVaOWgwrUf19gesAFokj5uCsWPqUNBP39pjobvbdHytSgT8yLL8O2S/obdz5xsmc2BJGetLtDWqy3HjgQfLlv6L1einHyM1hhCDj0D+0zITLgavexsqvgzOxMHChsgoc+Nyj0u6HEWy0eTBJIR1w+C7DeOoMHXE4eb02cTo0qWpNBhU0ZCW8ziiNNN/3CacRjETb1n6u7iUT0TULM28zusGRsWpBWgM/1imws+XJkjNnkUXdeXxwdT9Q6nZzqAsCTyeSM4vun1dVU74u/a1dwOj28D9fqaYAHJz7/ppyge8qTdwWQHVqdL65MywIDAQAB",
                    "utf-8",
                    "RSA2");
            //调用SDK验证签名

           /* boolean  signVerified = AlipaySignature.rsaCheckV1(
                    paramsMap,
                    "",
                    "utf-8",
                    "RSA2");  //调用SDK验证签名*/
            //2.是支付宝调用的
            if (signVerified){
                // TODO 验签成功后，按照支付结果异步通知中的描述，对支付结果中的业务内容进行二次校验，校验成功后在response中返回success并继续商户自身业务处理，校验失败返回failure
                System.out.println("验签成功。。。。。");
                //商户需要验证该通知数据中的 out_trade_no 是否为商户系统中创建的订单号；
                String out_trade_no = (String) paramsMap.get("out_trade_no");
                if(!out_trade_no.equalsIgnoreCase(orderno)) {
                    System.out.println("验签失败-> 订单号不正确");
                    response.getWriter().write("failure");
                    return;
                } else {
                    System.out.println("---->订单号正确，6666");
                }
                //判断 total_amount 是否确实为该订单的实际金额（即商户订单创建时的金额）；
                String total_amount = (String) paramsMap.get("total_amount");
                double m = Double.parseDouble(total_amount);
                if(m != money.doubleValue()) {
                    System.out.println("验签失败-> 金额不正确");
                    response.getWriter().write("failure");
                    return;
                } else {
                    System.out.println("---->金额正确，6666");
                }
                //验证 app_id 是否为该商户本身。
                String app_id = (String) paramsMap.get("app_id");
                if(!app_id.equalsIgnoreCase("2016103000779683")) {
                    System.out.println("验签失败-> appId不正确");
                    response.getWriter().write("failure");
                    return;
                } else {
                    System.out.println("---->appId正确，6666");
                }

                //校验通知中的 seller_id（或者 seller_email) 是否为 out_trade_no 这笔单据的对应的操作方（有的时候，一个商户可能有多个 seller_id/seller_email）；
                response.getWriter().write("success");

            } else {
                // TODO 验签失败则记录异常日志，并在response中返回failure.
                System.out.println("验签失败，不是支付宝的调用的接口......");
                response.getWriter().write("failure");
            }
        } catch (Exception e) {
            e.printStackTrace();
            System.out.println("验签失败-> " + e.getMessage() );
        }




    }

    /**
     * 支付接口
     * @param orderno
     * @param httpRequest
     * @param httpResponse
     * @throws ServletException
     * @throws IOException
     */
    @GetMapping("/returnurl")
    public void returnUrl(
            String orderno,
            HttpServletRequest httpRequest,
            HttpServletResponse httpResponse) throws ServletException, IOException {
        this.httpRequest = httpRequest;
        this.httpResponse = httpResponse;
        AlipayClient alipayClient = new DefaultAlipayClient(
                "https://openapi.alipaydev.com/gateway.do",   //支付网关
                "2016103000779683",   //商家ID
                //商家私钥
                "MIIEvgIBADANBgkqhkiG9w0BAQEFAASCBKgwggSkAgEAAoIBAQCvb0JGeLp4Jq4IJGE6F0TTI5M+ki4Gop0yLFKsJDVyHvZlmWMvz/rNZRm8aIVSry6krnErwmN48DbGfJSP8Dqvepn5UU8N+1aKcTeaEhUWwxrKS1j5EXCS8F7fs+zcdCD34O9aEOjcCzObHB4LTKDIAr5QiMCdp1WA4VG2CwHCp+McRvaNiPI3go4mwCLn0d/J7UQPQvQEhpIzpmwC1ZMY/gXF8EgP3Flj4AEQrBsOulxyoQSDmCCP/XQTQt3/9mADfDrT7x0aDvixKk7IdM3HQdcKWIskzEudVgTJcKpvq/g5ag+5jbOGQOBkZDtfVlWRaXcdcsk2wMypZGXvoLDBAgMBAAECggEBAI59gYkXmezpDcVTNx0ltSMA7CGQPY3qGl+cHHH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EiSg7b/R/0/GD2PvKWdM8qtr1KXf/d7Qj/DXsOvJor7uiIuxHZQ1sheoulx2pwQdNYb4ZqnlvhblojI3L4XFxJZmA",
                "JSON",   //格式
                "utf-8",  //编码
                //支付宝公钥
                aliPayPublicKey,
                //签名类型
                "RSA2");  //获得初始化的AlipayClient
        AlipayTradePagePayRequest alipayRequest = new AlipayTradePagePayRequest(); //创建API对应的request

        alipayRequest.setReturnUrl("http://crd7ru.natappfree.cc/pay/success");           //支付宝支付成功后回调接口
        alipayRequest.setNotifyUrl("http://crd7ru.natappfree.cc/pay/notifyurl?orderno=" + orderno + "&money=10000.00");         //在公共参数中设置回跳和通知地址
        //alipayRequest.setNotifyUrl("http://crd7ru.natappfree.cc/pay/notifyurl");         //在公共参数中设置回跳和通知地址
        alipayRequest.setBizContent("{" +
                //订单编号
                "    \"out_trade_no\":" + orderno + "," +
                "    \"product_code\":\"FAST_INSTANT_TRADE_PAY\"," +
                //支付金额
                "    \"total_amount\":10000.00," +
                "    \"subject\":\"Iphone12 600G\"," +
                "    \"body\":\"Iphone12 600G\"," +
                "    \"passback_params\":\"merchantBizType%3d3C%26merchantBizNo%3d2016010101111\"," +
                "    \"extend_params\":{" +
                "    \"sys_service_provider_id\":\"2088511833207846\"" +
                "    }" +
                "  }"); //填充业务参数
        String form = "";
        try {
            form = alipayClient.pageExecute(alipayRequest).getBody();  //调用SDK生成表单
        } catch (AlipayApiException e) {
            e.printStackTrace();
        }
        httpResponse.setContentType("text/html;charset=utf-8");
        httpResponse.getWriter().write(form); //直接将完整的表单html输出到页面
        httpResponse.getWriter().flush();
        httpResponse.getWriter().close();
    }


    /**
     * 支付成功后的回调，是由支付宝来调用的
     * @param model
     * @param total_amount
     * @return
     */
    @GetMapping("/success")
    public String success(Model model, String total_amount){
        model.addAttribute("money",total_amount);
        return "success";
    }

}
